package com.threeti.mecool.web.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.threeti.mecool.core.application.acl.UserService;
import com.threeti.mecool.core.domain.model.acl.User;
import com.threeti.mecool.core.infrastructure.persistence.acl.PermRoleRepository;
import com.threeti.mecool.legacy.infrastructure.persistence.EmployeeLegacyRepository;
import com.threeti.mecool.web.assembler.UserAssembler;
import com.threeti.mecool.web.form.UserForm;
import com.threeti.mecool.web.util.WebResponse;

@Controller
@RequestMapping("/auth")
public class AuthController {
  public static final Logger logger = LoggerFactory.getLogger(AuthController.class);

  @Autowired
  private UserService userService;

  @Autowired
  private PermRoleRepository permRoleRepo;
  
  @Autowired
  private EmployeeLegacyRepository empLegRepo;

  @RequestMapping(value = "/login.html")
  public String login(@RequestParam(value = "login_error", required = false) boolean error, Map modelMap,
      HttpServletRequest currentRequest, HttpServletResponse response) {
    if (error) {
      modelMap.put("error", "用户名或密码不正确");
    }
    
    // 禁止session失效重登陆在iframe外层打开原url
    HttpSession session = currentRequest.getSession(false);
    if (session != null) {
      session.removeAttribute("SPRING_SECURITY_SAVED_REQUEST");
    }

    return "/auth/login";
  }

  @RequestMapping(value = "/denied.html")
  public String denied() {
    return "/auth/denied";
  }

  @RequestMapping(value = "/register.html")
  public String registerPage(UserForm userForm) {
    userForm.setRoles(permRoleRepo.findAll());
    return "/admin/newUserForm";
  }

  @RequestMapping(value = "/doregister.html")
  public String register(UserForm userForm,Map modelMap) {
    try {
    	User user = UserAssembler.toDomWithPermissionEntries(userForm, permRoleRepo);
    	userService.register(user);
    	WebResponse.newInstance()
    			   .buildModelMapData(modelMap);
    } catch (Exception e) {
    	logger.error("新增帐号异常", e);
    	WebResponse.newInstance()
    			   .setExceptionMsg(e)
    			   .buildModelMapData(modelMap);
    }
    return WebResponse.GLOBAL_SUBMIT_CALLBACK_PAGE;
  }
}
